<?php
class Controller_Ticket extends Core_Controller
{
    protected $allowForHttp = array('_comment','_update','_load','_add','_bookHours');

    public function __construct(Core_Request $request) {
        parent::__construct($request);
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_JSON);
    }

    public function _comment()
    {
        $ticketData = $this->request->getPostData();
        $this->view->set(array(
                'success' => true,
                'message' => 'Comment added to Ticket #'.$ticketData['ticketId'],
                'comment' => array('date' => date('Y-m-d H:i'), 'user' => $this->getRandomDude(), 'comment' =>  $ticketData['comment'])
        ));
    }
    
    public function _update()
    {
        $ticketData = $this->request->getPostData();
        $this->view->set(array(
                'success' => true,
                'message' => 'Ticket #'.$ticketData['ticketId'].' set to state '.$ticketData['scrumState'],
                'additional' => $ticketData
        ));
    }

    protected $loadRules = array(
        'scrumState' => array('type' => 'integer', 'minValue' => 1),
        'sprint' => array('type' => 'integer', 'minValue' => 1, 'allowNull' => true),
        'product' => array('type' => 'integer', 'minValue' => 1, 'allowNull' => true),
        'assignee' => array('type' => 'integer', 'minValue' => 1, 'allowNull' => true)
    );
    public function _load()
    {
        $this->request->setValidationRules($this->loadRules);
        $scrumState = (INT)$this->getParamOrValue('scrumState');
        $sprintId = $this->postParamOrValue('sprint', null);
        $productId = $this->postParamOrValue('product', null);
        $assigneeId = $this->postParamOrValue('assignee', null);

        try
        {
            $ticketManager = new Model_TicketManager();
            $this->returnData($ticketManager->getTicketsWithCriteria(
                    $scrumState, $sprintId, $productId, $assigneeId));
        }
        catch(Core_Exception $e)
        {
            $this->returnErrorMessage($e->getMessage());
        }
        catch(Exception $error)
        {
            $this->returnGenericError($error->getMessage());
        }
    }

    protected $addRules = array(
        'name' => array('type' => 'string', 'minLength' => 3),
        'description' => array('type' => 'string', 'allowNull' => true),
        'sprint' => array('type' => 'integer', 'allowNull' => true),
        'product' => array('type' => 'integer', 'allowNull' => true),
        'assignee' => array('type' => 'integer', 'allowNull' => true),
        'originalEstimate' => array('type' => 'string', 'allowNull' => true),
        'ticketColor' => array('type' => 'string', 'allowNull' => true)
    );
    public function _add()
    {
        $this->request->setValidationRules($this->addRules);
        $this->request->replaceEmptyStringsWithNulls();
        $ticketData = array(
            'name' => $this->request->getPostData('name'),
            'description' => $this->request->getPostData('description'),
            'sprintId' => $this->request->getPostData('sprint'),
            'productId' => $this->request->getPostData('product'),
            'assigneeId' => $this->request->getPostData('assignee'),
            'originalEstimate' => self::estimateToHours(
                $this->request->getPostData('originalEstimate')),
            'remaining' => self::estimateToHours(
                $this->request->getPostData('originalEstimate')),
            'ticketColor' => $this->request->getPostData('ticketColor')
        );
        try
        {
            $ticketManager = new Model_TicketManager();
            $data = $ticketManager->create($ticketData, $this->getUserId());
            $this->returnData($data,
                    'Ticket #'.$data['id'].' '.$data['name'].' added', 1);
        } catch (Exception $e1) {
            $this->returnGenericError($e1->getMessage());
        }
    }

    private static function estimateToHours($estimate)
    {
        if(is_numeric($estimate))
            return (int)$estimate;
        else if(substr($estimate, -1) == 'h')
        {
            return (int)trim(substr($estimate,0,-1));
        }
        else if(substr($estimate, -1) == 'd')
        {
            return (int)trim(substr($estimate,0, -1))*6;
        }
        else
            return 0;
    }

    private function getBogusTicket($scrumState)
    {
        return array(
                'ticketId' => rand (1, 9000)
                , 'scrumState' => $scrumState
                , 'previousState' => 'backlog'
                , 'assigneeId' => rand(1,10)
                , 'assignee' => $this->getRandomDude()
                , 'name' => $this->getRandomName()
                , 'useCase'  => $this->getRandomString()
                , 'productId'  => 4
                , 'product' => 'Netpak2'
                , 'colorCls' => $this->getRandomClass()
                , 'previousCls' => $this->getRandomClass()
                , 'estimate' => rand(1,12)
                , 'originalEstimate' => rand(1,12)
                , 'usedTime' => rand(0,6)
                , 'comments' => array(
                    array('date' => '2011-02-03 12:34', 'userId' => 2, 'user' => 'Keijo', 'comment' => 'Keijon testikommentti')
                    ,array('date' => '2011-02-03 12:34', 'userId' => 9, 'user' => 'Jouko', 'comment' => 'Jouko kommentoi tikettiä')
                    ,array('date' => '2011-02-03 12:34', 'userId' => 5, 'user' => 'Matti', 'comment' => 'Varokaa Nykäsen Mattia')
                )
        );
    }

    private function getRandomClass ()
    {
        $classes = array(
            'c000000',
            'c993300','c333300','c003300','c003366','c333399','c808080','c3366FF','cFF99CC','cFFFFFF'
        );
        return $classes[rand(0, sizeof($classes)-1)];
    }

    private function getRandomDude()
    {
        return $this->randomDude[rand(0, sizeof($this->randomDude)-1)];
    }

    private $randomDude = array(
            'Elmeri', 'Root', 'Lea', 'Harri', 'Aku', 'Titta', 'Veikko', 'Kari'
    );

    private function getRandomName()
    {
        return $this->randomName[rand(0, sizeof($this->randomDude)-1)];
    }

    private $randomName = array(
            'Tee sitä ja tätä', 'Koodaa luokka', 'EHO dokumentaatio', 'EDB-MPJ varmennuskonversio', 'Keitä kahvia', 'Tuo pullaa kaupasta', 'Userstory 15.4', 'Mee himaan'
    );

    private function getRandomString()
    {
        $text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.';
        $output = '';
        for($i = 0; $i < rand(1, 3); $i++)
        {
            $output .= substr($text, 0, (int)rand(strlen($text)/100, strlen($text)))."\n\n";
        }
        return $output;
    }

    public function _bookHours()
    {
        $input = $this->request->getPostData();
        $this->view->set(array(
            'success' => true,
            'message' => $input['hours'].' h booked to ticket #'.$input['ticketID'],
            'hours' => $input['hours'],
            'comment' => $input['comment'] 
                        ? array('date' => date('Y-m-d H:i'), 'user' => $this->getRandomDude(), 'comment' =>  $input['comment'])
                        : null
        ));
    }
}
